import Vue from 'vue'
import VueRouter, { RouteConfig } from 'vue-router'
import IndexView from '@/views/IndexView.vue';
import LoginView from '@/views/LoginView.vue'
import HomeView from '@/views/HomeView.vue'
import UserView from '@/views/UserView.vue';
import RegisterView from '@/views/RegisterView.vue';
import NotFoundView from '@/views/404View.vue';
import PanelView from '@/views/NotesPanelView.vue';
import UtilView from '@/views/UtilView.vue';
import NotebookEditorView from '@/views/NotebookEditorView.vue';
import NotebookInfoView from '@/views/NotebookInfoView.vue';
import storageUtil from '@/util/StorageUtil.js';
import axiosInstance from '@/util/AxiosUtil.js';
import apis from '@/util/ApiUrls.js';

Vue.use(VueRouter)

export const URLS = {
  any: "*", // 任意
  root: "/", // 根路径
  notebook: "/notebook",
  login: "/notebook/login", // 登录
  loginName: "login",
  register: "/notebook/register", // 注册
  registerName: "register",
  index: "/notebook/index", // 索引页
  home: "/notebook/main", // 主页面
  homeName: "main",
  new: "/notebook/new", // 新建笔记
  newName: "new", // 新建笔记
  edit: "/notebook/edit/:id", // 修改笔记
  editName: "edit", // 修改笔记
  view: "/notebook/view/:id", // 查看笔记
  viewName: "view", // 查看笔记

  // user
  user: "/notebook/user", // 用户详细
  userName: "user"
}

/**
 * 定义路由
 */
const routes: Array<RouteConfig> = [
  {
    path: URLS.root,
    redirect: URLS.login,
  },
  {
    path: URLS.register,
    name: URLS.registerName,
    component: RegisterView
  },
  {
    path: URLS.login,
    name: URLS.loginName,
    component: LoginView
  },
  {
    path: URLS.index,
    name: 'index',
    component: IndexView
  },
  {
    path: URLS.home,
    name: URLS.homeName,
    component: HomeView,
    // 嵌套路由
    children: [
      // 笔记本控制面板
      {
        path: 'panel',
        component: PanelView
      },
      // 用户中心
      {
        path: 'user',
        component: UserView
      },
      // 小工具
      {
        path: 'util',
        component: UtilView
      },
    ]
  },
  {
    path: URLS.new,
    name: URLS.newName,
    component: NotebookEditorView
  },
  {
    path: URLS.edit,
    name: URLS.editName,
    component: NotebookEditorView
  },
  {
    path: URLS.view,
    name: URLS.viewName,
    component: NotebookInfoView
  },
  {
    path: URLS.any,
    component: NotFoundView
  },
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

/**
 * 全局前置守卫拦截器
 */
router.beforeEach((to, from, next) => {
  // 调用next() 后才是真正结束
  if (to.path === URLS.login || to.path === URLS.register) {
    // 登录和注册不拦截
    next();
  } else {
    const metaData = storageUtil.get();
    if (metaData.isLogin) {

      if (window.refreshInt === undefined) {
        refresh();
        window.refreshInt = window.setInterval(() => {
          // 定时刷新Token
          refresh();
        }, 1000 * 5 * 60); // 5分钟一次,有两个周期的buffer
      }

      // 已经登录的不拦截
      if (to.path === URLS.notebook || to.path === URLS.notebook + "/") {
        next({
          path: URLS.home
        });
      } else {
        next();
      }
    } else {
      next({
        path: URLS.login
      });
    }
  }

});

/**
 * 定时刷新token
 */
const refresh = () => {
  const metaData = storageUtil.get();
  // 超时自动重连-后台生成loginMills的时间比token早,所以不会出现token先过期的情况
  const loginMills = parseInt(metaData.loginMills, 10);
  // 此处给一个20分钟的buffer-给两个周期的缓冲,防止出现误差导致无法及时刷新
  if (Date.now() - loginMills > (20 * 60 * 1000)) {
    // 认为当前token超时了-自动通过刷新token获取新的token
    axiosInstance.post(apis.api_auth.refresh, undefined, { headers: { RefreshToken: metaData.refreshToken } }).then((res: any) => {
      // 刷新的token存入存储
      storageUtil.add("loginMills", res.data.LoginMills);
      storageUtil.add("authorization", res.data.Authorization);
    }).catch((e: any) => {
      // 续约失败则本周期内的访问不受限制
      console.log("自动续约异常", e)
    })
  }
}


export default router
